package com.wjm.defpermissiondemo;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

/**
 * //多个权限逻辑参考：https://blog.csdn.net/jianesrq0724/article/details/55211918
 * 多个权限回调逻辑还有问题，待优化
 */
public class MainActivity extends AppCompatActivity {

    private int oneRequestCode = 010;//3个权限请求码-默认进来界面就去拿所有权限，默认授权不执行业务
    private int startPage = 100;//3个权限请求码-默认进来界面就去拿所有权限，默认授权不执行业务
    private int updatePhoto = 123;//3个权限请求码-上传图片，选相版拍照上传
    private int updateVodio = 456;//3个权限请求码-上传视频，打开视频界面，拍视频上传

    //多个权限逻辑参考：https://blog.csdn.net/jianesrq0724/article/details/55211918
    String[] permissions = new String[]{Manifest.permission.RECORD_AUDIO, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.READ_CALENDAR, Manifest.permission.READ_CALL_LOG, Manifest.permission.WRITE_CONTACTS, Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};


//    String[] permissions = new String[]{  Manifest.permission.BODY_SENSORS };传感器 权限也不用申请(意思是没有申请弹框)
//    String[] permissions = new String[]{Manifest.permission.READ_SMS};//    短信权限不用申请(意思是没有申请弹框)
//    String[] permissions = new String[]{Manifest.permission.READ_SMS, Manifest.permission.RECEIVE_WAP_PUSH, Manifest.permission.RECEIVE_MMS, Manifest.permission.RECEIVE_SMS ,Manifest.permission.SEND_SMS/*,Manifest.permission.READ_CELL_BROADCASTS*/};(意思是没有申请弹框)


    /**
     * 要多个权限
     */
    private void twoPermissions(String[] permissions, int requestCode) {

        /**
         * 判断哪些权限未授予
         */
        List<String> permissionList = new ArrayList<>();
        for (int i = 0; i < permissions.length; i++) {
            if (ContextCompat.checkSelfPermission(this, permissions[i]) != PackageManager.PERMISSION_GRANTED) {
                permissionList.add(permissions[i]);
            }
        }

        /**
         * 判断是否为空
         */
        if (permissionList.isEmpty()) {//未授予的权限为空，表示都授予了
            delayEntryPage(requestCode);
        } else {//请求权限方法
            String[] permissionsArr = permissionList.toArray(new String[permissionList.size()]);//将List转为数组
            ActivityCompat.requestPermissions(this, permissionsArr, requestCode);
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

//        //部分手机上，可能会出现grantResult length为0的情况
//        if (grantResults.length == 0) {
//            mPermissionListener.onPermissionDenied();
//            return;
//        }

        if (oneRequestCode == requestCode) {

            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                callPhone();
            } else {
                String str = "权限被拒绝：权限=" + permissions.toString() + "\ngrantResults=" + grantResults.toString();
                Log.d("TAG", str);
                Toast.makeText(this, str, Toast.LENGTH_SHORT).show();

                //在这里可以处理“不再询问”选项
                if (!ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CALL_PHONE)) {
                    AlertDialog dialog = new AlertDialog.Builder(this).setMessage("该功能需要访问电话权限，不开启无法正常工作！")
                            .setPositiveButton("确定 ", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    PermissionUtils.startSettActivity(MainActivity.this);
                                }
                            }).create();
                    dialog.show();
                }
            }
            return;//响应，并处理掉回调,就是结束不传给系统
        } else if (startPage == requestCode || updatePhoto == requestCode || updateVodio == requestCode) {//456
            List<String> permissionList = new ArrayList<>();
            for (int i = 0; i < grantResults.length; i++) {
                if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {//没获取到多个权限中的指定权限
                    //判断是否勾选禁止后不再询问
                    boolean showRequestPermission = ActivityCompat.shouldShowRequestPermissionRationale(this, permissions[i]);
                    if (showRequestPermission) {//不是 再去重新申请
//                        twoPermissions();//重新申请权限
                        return;
                    } else {//是的 要去打开设置界面
                        permissionList.add(permissions[i]);
                    }
                }
            }
            //判断是禁止了权限弹框就弹出提示，手动跳设置开权限才能用
            if (null != permissionList && permissionList.size() > 0) {
                String sbStr = PermissionUtils.getPermissionStr(permissionList);
                AlertDialog dialog = new AlertDialog.Builder(this).setMessage("该功能需要开启 " + sbStr + " 权限，不开启无法正常工作！")
                        .setPositiveButton("知道了，去设置中手动开启 ", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                PermissionUtils.startSettActivity(MainActivity.this);
                            }
                        })
                        .create();
                dialog.show();
            } else {
                //权限都获取到了，可以去做操作了
                delayEntryPage(requestCode);
            }
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Toast.makeText(this, "进界面告诉用户，我要多个权限，快给我授权", Toast.LENGTH_SHORT).show();


        String[] permissions = new String[]{Manifest.permission.RECORD_AUDIO, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.READ_CALENDAR, Manifest.permission.READ_CALL_LOG, Manifest.permission.WRITE_CONTACTS, Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
        twoPermissions(permissions, startPage);
    }

    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.btn_one) {
            call();//单个权限
        } else if (id == R.id.btn_two_update_photo) {
            Toast.makeText(this, "上传头像要多个权限，快给我授权", Toast.LENGTH_SHORT).show();
            String[] permissions = new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
            twoPermissions(permissions, updatePhoto);//要2个权限 相机 和 sdcard
        } else if (id == R.id.btn_two_update_vodio) {
            Toast.makeText(this, "上传视频要多个权限，快给我授权", Toast.LENGTH_SHORT).show();
            String[] permissions = new String[]{Manifest.permission.RECORD_AUDIO, Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
            twoPermissions(permissions, updateVodio);//要3个权限 录音 相机 sdcard
        }
    }

    /**
     * 获取到权限，功能代码在些写，并要通过请求码区分业务功能是哪一个
     *
     * @param requestCode
     */
    private void delayEntryPage(int requestCode) {
        String text = "";
        if (updatePhoto == requestCode) {
            text = "权限都有了，执行业务一：上传头像";
        } else if (updateVodio == requestCode) {
            text = "权限都有了，执行业务二：上传视频";
        }
        Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
    }

    private void call() {
        //检查是否有指定权限
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
            //如果没有，就申请
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CALL_PHONE}, oneRequestCode);
        } else {//有就直接执行业务
            callPhone();
        }
    }


    private void callPhone() {
        Intent intent = new Intent(Intent.ACTION_CALL);
        Uri data = Uri.parse("tel:" + "10086");
        intent.setData(data);
        try {
            startActivity(intent);
        } catch (SecurityException e) {
            e.printStackTrace();
        }
    }


}


